import json
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# 创建浏览器对象
browser = webdriver.Chrome()
# 等待变量 是用来解析网页的
wait = WebDriverWait(browser, 10)

# 执行淘宝搜索动作
def taobaoSearch():
    # 打开淘宝网
    browser.get('https://www.taobao.com/')
    locater = (By.ID, 'q')
    # 等待搜索框加载完成
    wait.until(EC.presence_of_element_located(locater))
    # 在搜索框中传入内容
    input_search = browser.find_element_by_id('q')
    input_search.send_keys('篮球')
    # 执行搜索
    # //*[@id="J_TSearchForm"]/div[1]/button
    search_btn = browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button')
    search_btn.click()

# 模拟登录
def moniLogin():
    browser.get('https://www.taobao.com/')
    browser.delete_all_cookies()
    with open('cookie_tao.json', 'r', encoding='utf-8') as f:
        listCookies = json.loads(f.read())
    print(listCookies)
    for cookie in listCookies:
        browser.add_cookie(
            {
                'domain': cookie['domain'],
                'name': cookie['name'],
                'value': cookie['value'],
                'path': '/',
                'expires': None
            }
        )

if __name__ == '__main__':
    moniLogin()
    taobaoSearch()